package top.jnaw.test.util.plugin;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import top.jnaw.test.model.UserRoles;
import top.jnaw.test.model.Users;


  public class myRealm extends AuthorizingRealm{


//    public myRealm(){
//      setAuthenticationTokenClass(CaptchaUsernamePasswordToken.class);
//    }
    public String getName() {
      return "myRealm";
    }

    /**
     * 认证回调函数,登录时调用.
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
      UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
      Users user = Shiros.findUserByLoginName(token.getUsername(),"");
      if (user != null) {
        return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
      } else {
        return null;
      }
    }

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
      String loginName = (String) principals.fromRealm(getName()).iterator().next();
      Users user = Shiros.findUserByLoginName(loginName,null);
      if (user != null) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(Shiros.getRoleNameList(loginName));
        for (UserRoles role : Shiros.getRoleList(loginName)) {
          info.addStringPermissions(Shiros.getPermissionNameListByRole(role.getRoleName()));
        }
        return info;
      } else {
        return null;
      }
    }

    /**
     * 更新用户授权信息缓存（不管用）
     * @principal 用户名
     */
    public void clearCachedAuthorizationInfo(String principal) {
      SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
      clearCachedAuthorizationInfo(principals);
    }

    /**
     * 清除所有用户授权信息缓存.
     */
    public void clearAllCachedAuthorizationInfo() {
      Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
      if (cache != null) {
        for (Object key : cache.keys()) {
          cache.remove(key);
        }
      }
    }

    /**
     * 重新赋值权限(在比如:给一个角色临时添加一个权限,需要调用此方法刷新权限,否则还是没有刚赋值的权限)
//     * @param myRealm 自定义的realm
     * @param username 用户名
     */
    public  void reloadAuthorizing(String username){
      RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
      myRealm shiroRealm = (myRealm)rsm.getRealms().iterator().next();
      Subject subject = SecurityUtils.getSubject();
      String realmName = subject.getPrincipals().getRealmNames().iterator().next();
//      logger.info("oper.user="+user.getEmail()+",login.user="+SecurityUtils.getSubject().getPrincipal().toString());

      //shiroRealm.clearAllCachedAuthorizationInfo2();//清楚所有用户权限
      //第一个参数为用户名,第二个参数为realmName,test想要操作权限的用户
      SimplePrincipalCollection principals = new SimplePrincipalCollection(username,realmName);
      subject.runAs(principals);
      shiroRealm.getAuthorizationCache().remove(subject.getPrincipals());
      shiroRealm.getAuthorizationCache().remove(username);
      subject.releaseRunAs();
    }

  }
